package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.Message;
import cn.wolfcode.trip.base.query.LettersQueryObject;
import cn.wolfcode.trip.base.query.MessageQueryObject;
import cn.wolfcode.trip.base.service.IPrivateLetterMessageService;
import cn.wolfcode.trip.base.util.JsonResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/privateLetters")
public class LetterMessageController {

    @Autowired
    private IPrivateLetterMessageService privateLetterMessageService;

    //保存私信内容
    @PostMapping
    public JsonResult save(Message message) {
        JsonResult result = new JsonResult();
        try {
            privateLetterMessageService.save(message);
        } catch (Exception e) {
            result.mark(e.getMessage());
        }
        return result;
    }

    //分页查询单个用户查询的所有消息
    @GetMapping("/sumLetters")
    public PageInfo list(LettersQueryObject qo) {
        //按照发送时间正序排序
        qo.setOrderBy("m.sendTime ");
        int unReadCount = privateLetterMessageService.selectUnReadCount(qo);
        if(unReadCount == 0){
            qo.setState(null);
        }
        qo.setPageSize(0);
        return privateLetterMessageService.query(qo);
    }

    @GetMapping("/counts")
    public PageInfo listCounts(LettersQueryObject qo) {
        //按照发送时间正序排序
        PageInfo pageInfo = null;
        qo.setOrderBy("m.sendTime ");
        int unReadCount = privateLetterMessageService.selectUnReadCount(qo);
        if(unReadCount == 0){
            qo.setState(null);
        }
        pageInfo = privateLetterMessageService.letterForList(qo);

        return pageInfo;
    }

    @PutMapping("/state")
    public void changeMsgState(MessageQueryObject qo){
        qo.setSeeTime(new Date());
        privateLetterMessageService.changeMsgState(qo);
    }

}
